package com.anji.plus.ajpushlibrary.util;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.anji.plus.ajpushlibrary.AppSpPushLog;
import com.anji.plus.ajpushlibrary.AppSpPushConstant;
import com.anji.plus.ajpushlibrary.base.ActionType;
import com.anji.plus.ajpushlibrary.model.NotificationMessageModel;

/**
 * Copyright © 2018 anji-plus
 * 安吉加加信息技术有限公司
 * http://www.anji-plus.com
 * All rights reserved.
 * <p>
 * 消息处理，监听到达的消息和处理点击消息事件
 * </p>
 */
public class MessageUtil {
    /**
     * @param context
     * @param title   消息标题
     * @param message 消息内容
     * @param extra   其他配置，比如{“key1":”value1“,“key2":”value2“}，以json格式返回，详情见appsp官网推送
     */
    public static void onMessageArrived(Context context, String messageId, String title, String message, String extra) {
        AppSpPushLog.i("onMessageArrived is called. " + message.toString());
        try {
            //消息去重处理
            String cachedMesssageId = (String) SPUtil.get(context, "messsageId", "");
            if (cachedMesssageId == messageId) {
                return;
            }
            SPUtil.put(context, "messsageId", cachedMesssageId);
            Intent intent = new Intent();
            intent.setAction(AppSpPushConstant.MESSAGE_RECEIVED_ACTION);
            Bundle bundle = new Bundle();
            NotificationMessageModel notificationMessageModel = new NotificationMessageModel();
            notificationMessageModel.setTitle(title);
            notificationMessageModel.setContent(message);
            notificationMessageModel.setNotificationExtras(extra);
            notificationMessageModel.setActionType(ActionType.NONE);
            bundle.putSerializable(AppSpPushConstant.HNOTIFICATIONMESSAGE, notificationMessageModel);
            intent.putExtras(bundle);
            context.sendBroadcast(intent);
        } catch (Throwable throwable) {

        }
    }

    /**
     * @param context
     * @param title   消息标题
     * @param message 消息内容
     * @param extra   其他配置，比如{“key1":”value1“,“key2":”value2“}，以json格式返回，详情见appsp官网推送
     */
    public static void onMessageClicked(Context context, String title, String message, String extra) {
        try {
            Intent intent = new Intent();
            intent.setAction(AppSpPushConstant.MESSAGE_RECEIVED_ACTION);
            Bundle bundle = new Bundle();
            NotificationMessageModel notificationMessageModel = new NotificationMessageModel();
            notificationMessageModel.setTitle(title);
            notificationMessageModel.setContent(message);
            notificationMessageModel.setNotificationExtras(extra);
            notificationMessageModel.setActionType(ActionType.CLICK);
            bundle.putSerializable(AppSpPushConstant.HNOTIFICATIONMESSAGE, notificationMessageModel);
            intent.putExtras(bundle);
            context.sendBroadcast(intent);
        } catch (Throwable throwable) {

        }
    }
}
